﻿package bdz.common.utils
{
	import bdz.common.events.GenericEvent;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	/**
	 * ...
	 * @author ...
	 */
	public class GlobalRender extends EventDispatcher
	{
		
		private static var instance:GlobalRender;
		private var _timer:Timer;
		private var sprite:Sprite;
		
		public var useTime:Boolean = false;
		function GlobalRender(se:SingletonEnforcer) {
			
		}
		private function initialize(fps:Number = 61):void {
			if(!useTime){
				sprite = new Sprite();
				sprite.addEventListener(Event.ENTER_FRAME, onTimerTick);
			}else{			
				_timer = new Timer(1, 0);
				_timer.start();
				_timer.addEventListener(TimerEvent.TIMER, onTimerTick);
			}
			
		}
		
		private function onTimerTick(evt:* = null):void {
			dispatchEvent(new GenericEvent(GenericEvent.PROGRESS, evt));
			try{
				evt.updateAfterEvent();	
			}catch (e:Error) {
				
			}
		}
		public static function getInstance(fps:Number = 61):GlobalRender {
			if (instance == null) {
				instance = new GlobalRender(new SingletonEnforcer());
				instance.initialize(fps);
			}
			return instance;
		}
		public function resume():void {
			if(!useTime){
				sprite.addEventListener(Event.ENTER_FRAME, onTimerTick);
			}else{
				_timer.start();
			}
		}
		public function pause():void {
			if(!useTime){
				sprite.removeEventListener(Event.ENTER_FRAME, onTimerTick);
			}else{
				_timer.stop();
			}
			
		}
	}
	
}
/**
 * @private
 * 
 */
internal class SingletonEnforcer{}